package com.iotboss.device.consumer;

import com.alibaba.fastjson2.JSON;
import com.github.crab2died.ExcelUtils;
import com.iotboss.common.entity.device;
import com.iotboss.common.entity.outDeviceEnd;
import com.iotboss.common.mapper.mysql.orUtilMapper.IotOrDeviceMapper;
import com.iotboss.common.utils.yunze.VeDate;
import com.iotboss.common.mapper.mysql.IotDeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 卡导入消费者
 */
@Slf4j
@Component
public class importDeviceConsumer {


    @Resource
    private IotDeviceMapper iotDeviceMapper;//操作记录mapper
    @Resource
    private IotOrDeviceMapper iotOrDeviceMapper;



    @RabbitHandler
    @RabbitListener(queues = "admin_saveDevice_queue")
    public void importDevice(String msg){
        if (StringUtils.isEmpty(msg)) {//判断是否为空
            return;
        }
        Map<String, Object> map = JSON.parseObject(msg);//转化json
        String readName = map.get("ReadName").toString();//上传文件 名称  "/mnt/file/54a10bc1b755467ab445e158b30f8836设备导入模板_1699175414459.xlsx"
        String newName = map.get("newName").toString(); //执行结束后 生成结果时的 文件名称
        Map<String, Object> userMap = (Map<String, Object>) map.get("User"); // 登录用户信息
        String filePath = map.get("filePath").toString();//根路径 "E:\dir\iot"
        String type = map.get("type").toString(); // 类型  "importDeviceData"
        String id = map.get("id").toString(); // or_device表里面的 主键 id
        //读取 导入的文件
        String path = filePath+readName;//生成文件完整路径
        try{
            List<device> deviceList = ExcelUtils.getInstance().readExcel2Objects(path, device.class, 0, 0);//读出来的 DeviceList
            List<outDeviceEnd> endList = new ArrayList<outDeviceEnd>();//导入结果Excl
            Map<String, Object> insertMap = new HashMap<String, Object>();//导入参数mapper
            int insertNumber=0;
            if (deviceList.size()>0){  // 上传的文件不为空

                for (int i = 0; i <deviceList.size(); i++) { //遍历读出来的list

                    try{
                        //将数据插入数据库
                        outDeviceEnd outDeviceEnd = new outDeviceEnd();
                        device device = deviceList.get(i);
                        insertMap.put("model",device.getModel());
                        outDeviceEnd.setModel(device.getModel().toString());
                        insertMap.put("box",device.getBox());
                        outDeviceEnd.setBox(device.getBox().toString());
                        insertMap.put("reel",device.getReel());
                        outDeviceEnd.setReel(device.getReel().toString());
                        if (device.getImei()!=null){
                            insertMap.put("imei",device.getImei());
                            outDeviceEnd.setImei(device.getImei().toString());
                        }
                        if (device.getBatch()!=null){
                            insertMap.put("batch",device.getBatch());
                            outDeviceEnd.setBatch(device.getBatch().toString());
                        }
                        if (device.getIccid()!=null){
                            insertMap.put("iccid",device.getIccid());
                            outDeviceEnd.setIccid(device.getIccid().toString());
                        }
                        if (device.getSn()!=null){
                            insertMap.put("sn",device.getSn());
                            outDeviceEnd.setSn(device.getSn().toString());
                        }
                        if (device.getImsi()!=null){
                            insertMap.put("imsi",device.getImsi());
                            outDeviceEnd.setImsi(device.getImsi().toString());
                        }
                        insertMap.put("type","0");
                        insertMap.put("dept_id",userMap.get("deptId"));
                        try{
                            //存之前需要判断 imei是否存在于 数据苦衷
                            String existImei = iotDeviceMapper.isExistImei(insertMap);
                            if (existImei!=null){
                                outDeviceEnd.setEnd("导入失败");
                                outDeviceEnd.setReason("imei已存在");
                                outDeviceEnd.setCreateTime(VeDate.getYYYYMMDDhhmmss());
                            }else {
                                iotDeviceMapper.insertDevice(insertMap);//执行插入
                                //插入成功 导出list存入导入结果list
                                outDeviceEnd.setEnd("导入成功");
                                outDeviceEnd.setReason("200");
                                outDeviceEnd.setCreateTime(VeDate.getYYYYMMDDhhmmss());
                                insertNumber = insertNumber+1;
                            }

                        }catch (Exception e){
                            //插入失败 导出List存入导入结果List
                            outDeviceEnd.setEnd("导入失败");
                            outDeviceEnd.setReason(e.getMessage());
                            outDeviceEnd.setCreateTime(VeDate.getYYYYMMDDhhmmss());
                        }
                        //将导出结果对象添加到endList中
                       endList.add(outDeviceEnd);

                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
                //循环结束 导出 导入结果
                try{
                    String outPath = filePath+"/mnt/file";
                    String outName = UUID.randomUUID().toString().replace("-", "") + "importDeviceData.xlsx";;
                    String outFile = outPath+"/"+outName;
                    ExcelUtils.getInstance().exportObjects2Excel(endList, outDeviceEnd.class, true, null, true,outFile);
                    //将 消费结果 插入 or_device表 end_time end_path o_type insert_number
                    Map<String, Object> endOrInsertMap = new HashMap<>();
                    endOrInsertMap.put("end_path",outFile);
                    endOrInsertMap.put("insertNumber",insertNumber);
                    endOrInsertMap.put("id",id);
                    iotOrDeviceMapper.endInsert(endOrInsertMap);
                }catch(Exception e){
                    log.error("设备导入-消费者-导出文件异常");
                }
            }else {
                //如果传入的文件为空 则停止输出
            }


        }catch (Exception e){
            e.printStackTrace();
            log.error("设备导入-消费者-导入文件读取异常");
        }


    }

    @RabbitHandler
    @RabbitListener(queues = "dlx_admin_saveDevice_queue")
    public void DlximportDevice(){

    }

    public static void main(String[] args) {
        String s = UUID.randomUUID().toString().replace("-", "") + "importDeviceData.xlsx";
        System.out.println(s);
    }
}
